<template>
  <div style="width: 100%">
    <div v-if="$slots.headerTop" style="margin: 5px">
      <slot name="headerTop"></slot>
    </div>
    <div class="flex items-center justify-between">
      <slot name="tableTitle" v-if="$slots.tableTitle"></slot>
      <TableTitle
        :helpMessage="titleHelpMessage"
        :title="title"
        v-if="!$slots.tableTitle && title"
      />
      <div class="flex items-center" :class="`${prefixCls}__toolbar`">
        <a-button
          type="primary"
          v-if="options?.add?.show && hasPermission(options?.add?.permission)"
          preIcon="ant-design:plus-outlined"
          @click="handleCreate"
        >
          新增
        </a-button>
        <a-button
          @click="handleExport"
          v-if="
            options?.export?.show && hasPermission(options?.export?.permission)
          "
          preIcon="ant-design:file-excel-outlined"
          :loading="exportLoading"
        >
          导出
        </a-button>
        <Popconfirm
          title="确定删除吗?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleRemove"
        >
          <a-button
            danger
            v-if="
              getRowSelection &&
              getRowSelection()?.selectedRowKeys?.length &&
              options?.delete?.show &&
              hasPermission(options?.delete.permission)
            "
            >删除</a-button
          >
        </Popconfirm>
        <slot name="toolbar"></slot>
        <Divider type="vertical" v-if="$slots.toolbar && showTableSetting" />
        <!-- <TableSetting
          :setting="tableSetting"
          :loadClear="loadClear"
          v-if="showTableSetting"
          @columns-change="handleColumnChange"
        /> -->
        <AdvancedQuery
          v-if="showHSearch"
          :columns="columns"
          :tableKey="tableSetting?.tableKey"
          :searchFormSchema="searchFormSchema"
          @advanced-search="handleSearch"
          @set-default="handleSetDefalut"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import type {
  TableSetting,
  ColumnChangeParam,
  BasicColumn,
  TableOptions,
} from '../types/table';
import type { PropType, Ref } from 'vue';
import { defineComponent, ref } from 'vue';
import { Divider, Popconfirm } from 'ant-design-vue';
import TableSettingComponent from './settings/index.vue';
import TableTitle from './TableTitle.vue';
import { useDesign } from '@/hooks/web/useDesign';
import { FormActionType, FormProps, FormSchema } from '@/components/Form';
import { useMessage } from '@/hooks/web/useMessage';
import { usePermission } from '@/hooks/web/usePermission';
import type { TableRowSelection } from '../types/table';
import AdvancedQuery from './advanced/AdvancedQuery.vue';
import { exportData, getData } from '@/utils/http/axios/component';
export default defineComponent({
  name: 'BasicTableHeader',
  components: {
    Divider,
    TableTitle,
    AdvancedQuery,
    Popconfirm,
    TableSetting: TableSettingComponent,
  },
  props: {
    title: {
      type: [Function, String] as PropType<
        string | ((data: Recordable) => string)
      >,
    },
    loadClear: {
      type: Boolean,
      default: true,
    },
    getRowSelection: {
      type: Function as PropType<() => TableRowSelection<any>>,
    },
    formRef: {
      type: Object as PropType<Ref<ComponentRef>>,
    },
    options: {
      type: Object as PropType<TableOptions>,
    },
    tableSetting: {
      type: Object as PropType<TableSetting>,
    },
    showHSearch: {
      type: Boolean,
    },
    showTableSetting: {
      type: Boolean,
    },
    columns: {
      type: Array as PropType<BasicColumn[]>,
      default: () => [],
    },
    searchFormSchema: {
      type: Array as PropType<FormSchema[]>,
    },
    titleHelpMessage: {
      type: [String, Array] as PropType<string | string[]>,
      default: '',
    },
  },
  emits: [
    'columns-change',
    'advanced-search',
    'advanced-set-default',
    'remove-success',
    'table-export',
  ],
  setup(_, { emit }) {
    const { hasPermission } = usePermission();
    const exportLoading = ref(false);
    const { createMessage } = useMessage();
    const { prefixCls } = useDesign('basic-table-header');
    const hSearchParams = ref();
    function handleColumnChange(data: ColumnChangeParam[]) {
      emit('columns-change', data);
    }
    const handleSearch = (params: Recordable) => {
      hSearchParams.value = params;
      emit('advanced-search', params);
    };
    const handleSetDefalut = (schemas: FormSchema[]) => {
      console.log(schemas, 'handleSetDefault');
      emit('advanced-set-default', schemas);
    };
    const handleCreate = () => {
      _.options?.add?.overFunction && _.options?.add.overFunction();
    };
    const handleExport = () => {
      if (!_.options?.export?.api) {
        createMessage.error('未配置表格导出api函数');
      } else {
        exportLoading.value = true;
        exportData(_.options.export.api, {
          ...(_.formRef!.value! as unknown as FormActionType).getFieldsValue(),
          ..._.options.export.params,
        })
          .then(() => {
            exportLoading.value = false;
          })
          .catch(() => {
            exportLoading.value = false;
          });
        emit('table-export');
      }
    };
    // 删除数据后触发事件通知表格重载reload
    const handleRemove = async () => {
      if (!_.options?.delete?.api) {
        createMessage.error('未配置表格删除api函数');
      } else {
        if (_.options.delete.before) {
          if (
            !_.options.delete.before(
              _.getRowSelection().selectedRowKeys as string[],
            )
          )
            return;
        }
        emit('remove-success');
      }
    };
    return {
      prefixCls,
      exportLoading,
      handleColumnChange,
      handleSearch,
      handleSetDefalut,
      handleCreate,
      handleExport,
      handleRemove,
      hasPermission,
    };
  },
});
</script>
<style lang="less">
@prefix-cls: ~'@{namespace}-basic-table-header';

.@{prefix-cls} {
  &__toolbar {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    > *:not(:last-child) {
      margin-right: 8px;
    }
  }
}
</style>
